﻿using PLCS.Application.Contracts.HisOrderApp;
using PLCS.Application.Contracts.HisOrderApp.Dtos;
using PLCS.Application.Contracts.HisTaskApp.Dtos;
using PLCS.Application.Contracts.Params;
using PLCS.Domain.Orders;
using PLCS.Domain.Tasks;
using Volo.Abp.Application.Dtos;

namespace PLCS.Application.HisOrderApp;

public class HisOrderAppService : CrudAppService<HisOrder, HisOrderDto, Guid, PagedResultRequestDto, HisOrderEditDto>, IHisOrderAppService
{
    private readonly IHisOrderRepository _hisOrderRepository;

    public HisOrderAppService(IHisOrderRepository repository) : base(repository)
    {
        _hisOrderRepository = repository;
    }

    public async Task<HisOrderDto> GetByOrderNoAsync(string orderNo)
    {
        var order = await _hisOrderRepository.FindHisOrderByNoAsync(orderNo);
        order = Check.NotNull(order, orderNo, $"工单‘{orderNo}’不存在");
        return ObjectMapper.Map<HisOrder, HisOrderDto>(order);
    }

    public async Task<PagedResultDto<HisOrderDto>> GetListBySearchAsync(PagedResultRequestDto input, string? orderNo, string? startTime, string? endTime)
    {
        await CheckGetListPolicyAsync();

        var query = await CreateFilteredQueryAsync(input);
        query = query.OrderByDescending(x => x.CreationTime);
        query = query.WhereIf(!string.IsNullOrEmpty(orderNo), x => x.OrderNo == orderNo);
        bool isStartTime = DateTime.TryParse(startTime, out DateTime StartDateTime);
        query = query.WhereIf(isStartTime, x => x.CreationTime > StartDateTime);
        bool isEndTime = DateTime.TryParse(endTime, out DateTime EndDateTime);
        query = query.WhereIf(isEndTime, x => x.CreationTime < EndDateTime);
        var totalCount = await AsyncExecuter.CountAsync(query);

        query = ApplyPaging(query, input);

        var entities = await AsyncExecuter.ToListAsync(query);
        var entityDtos = await MapToGetListOutputDtosAsync(entities);

        return new PagedResultDto<HisOrderDto>(
            totalCount,
            entityDtos
        );
    }
}